/**
 * 
 */
package com.zufangbao.earth.web.controller.system;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.web.interceptor.InfoMessage;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.zufangbao.earth.entity.particalsystem.AppParticles;
import com.zufangbao.earth.entity.particalsystem.Partical;
import com.zufangbao.earth.handler.FileHandler;
import com.zufangbao.earth.service.AppParticlesService;
import com.zufangbao.earth.service.ParticalService;
import com.zufangbao.sun.entity.Channel;
import com.zufangbao.sun.entity.company.corp.App;
import com.zufangbao.sun.entity.company.corp.AppAccount;
import com.zufangbao.sun.entity.company.corp.AppPaymentConfig;
import com.zufangbao.sun.entity.company.corp.AppServiceConfig;
import com.zufangbao.sun.entity.payment.config.PaymentInstitution;
import com.zufangbao.sun.entity.payment.config.PaymentInstitutionParam;
import com.zufangbao.sun.service.AppService;
import com.zufangbao.sun.service.PaymentInstitutionService;

/**
 * @author lute
 *
 */

@Controller
@RequestMapping("/apps")
@MenuSetting("menu-system")
public class AppController {
	
	@Autowired
	FileHandler fileHandler;
	
	@Autowired
	private AppService appService;
	
	@Autowired
	private PaymentInstitutionService paymentInstitutionService;
	
	@Autowired
	private AppParticlesService appParticlesService;
	
	@Autowired
	private ParticalService particalService;
	
	/**
	 * List all apps
	 * 
	 * @return
	 */
	@RequestMapping("")
	@MenuSetting("submenu-app")
	public ModelAndView list() {
		
		ModelAndView modelAndView = new ModelAndView("app/app-list");
		
		List<App> apps = appService.loadAll(App.class);
		modelAndView.addObject("apps", apps);
		
		return modelAndView;
	}
	/**
	 * Prepare to create app
	 * 
	 * @return
	 */
	@RequestMapping("/create")
	public String create() {
		return "app/app-create";
	}
	
	/**
	 * Create app
	 * 
	 * @param app
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.POST)
	@InfoMessage("info.app.create.success")
	public String onCreate(App app) {
		
		boolean exist_app = appService.create(app);
		if(exist_app){
			return "redirect:/apps/create-app-failure";
		}
		return "redirect:/apps";
	}
	@RequestMapping(value = "create-app-failure", method = RequestMethod.GET)
	@InfoMessage("info.app.create.failure")
	public String onCreateFailure(App app) {
		return "redirect:/apps";
	}
			
	/**
	 * Prepare to edit app Info 
	 * 
	 * @param appId
	 * @return
	 */
	@RequestMapping("/{appId}/info/edit")
	public ModelAndView editAppInfo(@PathVariable("appId") Long appId) {
		
		App app = appService.load(App.class, appId);
		
		ModelAndView modelAndView = new ModelAndView("app/app-info-edit");
		modelAndView.addObject("app", app);
		
		return modelAndView;
	}
	
	/**
	 * Edit app Info
	 * 
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/{appId}/info", method = RequestMethod.PATCH)
	@InfoMessage("info.app-info.edit.succsess")
	public String onEditAppInfo(@Preloading App app) {
		
		appService.update(app);

		return "redirect:/apps/";
	}
	
	/**
	 * Show app config by app and channel
	 * 
	 * @param appId
	 * @param channelString
	 * @return
	 */
	@RequestMapping("/{appId}/config")
	@MenuSetting("submenu-app")
	public ModelAndView config(@PathVariable("appId") Long appId, @RequestParam("channel") String channelString) {
		
		ModelAndView modelAndView = new ModelAndView("app/app-config");
		
		// parse channel
		Channel channel = Channel.aliasOf(channelString);
		modelAndView.addObject("channel", channel);
		
		// load app
		App app = appService.load(App.class, appId);
		modelAndView.addObject("app", app);
		
		// get app acount
		AppAccount account = appService.getAppAccount(app, channel);
		modelAndView.addObject("account", account);
		
		// get app service config
		List<AppServiceConfig> serviceConfigs = appService.getAppServiceConfig(app, channel);
		modelAndView.addObject("serviceConfigs", serviceConfigs);
		
		// get app payment institution config
		AppPaymentConfig appPaymentConfig = appService.getAppPaymentConifg(app, channel);
		
		if(appPaymentConfig != null) {
			
			// get payment institution params
			PaymentInstitution paymentInstitution = appPaymentConfig.getPaymentInstitution();
			List<PaymentInstitutionParam> paymentParams = paymentInstitutionService.getPaymentInstitutionParams(paymentInstitution, channel);
			modelAndView.addObject("paymentParams", paymentParams);
			
		}
		List<Partical> particalList = particalService.loadAllQuarks();
		
		List<AppParticles> appParticlesList = appParticlesService.getAppParticleByAppId(app.getAppId());
		
		modelAndView.addObject("particals", particalList);
		
		modelAndView.addObject("appParticles", appParticlesList);
		
		return modelAndView;
	}
	
	/**
	 * Prepare to edit app account
	 * 
	 * @param appId
	 * @return
	 */
	@RequestMapping("/{appId}/account/{accountId}/edit")
	public ModelAndView editAppAccount(@PathVariable("appId") Long appId, @PathVariable("accountId") Long accountId) {
		
		ModelAndView modelAndView = new ModelAndView("app/account/account-edit");
		
		App app = appService.load(App.class, appId);
		AppAccount account = appService.loadAppAccount(accountId);
		
		modelAndView.addObject("account", account);
		modelAndView.addObject("app", app);
		
		return modelAndView;
	}
	
	/**
	 * Prepare to edit app account
	 * 
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/{appId}/account/{accountId}", method = RequestMethod.PATCH)
	@InfoMessage("info.app-account.edit.success")
	public String onEditAppAccount(@Preloading AppAccount appAccount, @RequestParam(value = "logoImage", required = false) MultipartFile logoImage, @RequestParam(value = "headerImage", required = false) MultipartFile headerImage, @PathVariable("appId") Long appId,@PathVariable("accountId") Long accountId) throws Exception {
		
		// if logo changes, update logo image
		if(logoImage != null && !logoImage.isEmpty()) {
			String logoFileName = appAccount.getId() + logoImage.getOriginalFilename().substring(logoImage.getOriginalFilename().lastIndexOf("."));
			fileHandler.save(logoFileName, logoImage.getInputStream());
			appAccount.changeLogo(logoFileName);
		}
				
		// if header changes, update header image
		if(headerImage != null && !headerImage.isEmpty()) {
			String headerFileName = appAccount.getId() +"-logo"+ headerImage.getOriginalFilename().substring(headerImage.getOriginalFilename().lastIndexOf("."));
			fileHandler.save(headerFileName, headerImage.getInputStream());
			appAccount.changeHeader(headerFileName);
		}
		
		appService.updateAppAccount(appAccount);
		
		return "redirect:/apps/" + appId + "/config?channel=" + appAccount.getChannel().getDescription();
	}
	
}
